//
//  LocalData.swift
//  fruit-helper-swift
//
//  Created by 赵隆杰 on 2022/6/11.
//

import Foundation
import YTKKeyValueStore

class LocalData {
    private func fetchValueStore(table: String) -> YTKKeyValueStore {
        let store = YTKKeyValueStore.init(dbWithName: "book.db")
        store?.createTable(withName: table)
        return store!
    }
    private func fetchValueStore() -> YTKKeyValueStore {
        return fetchValueStore(table: bookTableName())
    }
    private func bookTableName() -> String {
        return "book_table";
    }
    private func bookKey() -> String {
        return "book";
    }
    private func bookAddKey() -> String {
        return "book_add";
    }
    private func bookFinishKey() -> String {
        return "book_finish";
    }
    private func dailyReminderTableName() -> String {
        return "dailyReminder_table";
    }
    private func dailyReminderKey() -> String {
        return "dailyReminder";
    }
    //-------------------------
    ///#pragma mark -
    ///存储一个书单
    private func saveBookInfoModel(infoModel: BookModel, bookKey: String) {
        let infoDic: [String: Any] = JsonUtil.modelToDictionary(infoModel)
        let dicBooks: Array<[String: String]> = getAlldicBooks_bookKey(bookKey: bookKey)
        var book_id: String = ""
        var index: Int = 0
        for dict in dicBooks {
            let dic_id = dict["book_id"]
            if Int(infoModel.book_id ?? "0") == Int(dic_id ?? "0") {
                book_id = dic_id!
                break
            }
            index += 1
        }
        let temDicBooks = NSMutableArray.init(array: dicBooks)
        if (!book_id.isEmpty) {
            temDicBooks.replaceObject(at: index, with: infoDic)
        } else {
            temDicBooks.insert(infoDic, at: 0)
        }
        fetchValueStore().put(temDicBooks, withId: bookKey, intoTable: bookTableName())
    }

    private func getAlldicBooks_bookKey(bookKey: String) -> Array<[String: String]> {
        guard fetchValueStore().getYTKKeyValueItem(byId: bookKey, fromTable: bookTableName()) != nil else {
            return []
        }
        guard let dicBooks = fetchValueStore().getObjectById(bookKey, fromTable: bookTableName()) else {
            return []
        }
        return dicBooks as! Array<[String : String]>
    }
    ///取出一个书单
    private func getBook(book_id: String, bookKey: String) -> BookModel {
        let dicBooks: Array<[String: String]> = getAlldicBooks_bookKey(bookKey: bookKey)
        var model = BookModel.init()
        for dict in dicBooks {
            if let dic_id = dict["book_id"] {
                if Int(book_id) == Int(dic_id) ?? 0 {
                    model = JsonUtil.dictionaryToModel(dict, BookModel.self) as! BookModel
                    break
                }
            }
            
        }
        return model
    }
    ///取出所有书单
    private func getAllBooks_bookKey(bookKey: String) -> Array<BookModel> {
        let dicBooks: Array<[String: Any]> = getAlldicBooks_bookKey(bookKey: bookKey)
        var temModelArr = Array<BookModel>.init()
        for dict in dicBooks {
            let model: BookModel = JsonUtil.dictionaryToModel(dict, BookModel.self) as! BookModel
            temModelArr.append(model)
        }
        return temModelArr
    }
    ///删除一个书单
    private func deleteBook(book_id: String, bookKey: String) {
        let dicBooks: Array<[String: String]> = getAlldicBooks_bookKey(bookKey: bookKey)
        let temDicBooks = NSMutableArray.init(array: dicBooks)
        var infoDict: [String: String] = [:]
        for dict in dicBooks {
            if let dic_id = dict["book_id"] {
                if Int(book_id) == Int(dic_id) ?? 0 {
                    infoDict = dict
                    break
                }
            }
            
        }
        if !infoDict.isEmpty {
            temDicBooks.remove(infoDict)
        }
        if temDicBooks.count == 0 {
            deleteAllBooks_bookKey(bookKey: bookKey)
        } else {
            fetchValueStore().put(temDicBooks, withId: bookKey, intoTable: bookTableName())
        }
    }
    ///删除所有书单
    private func deleteAllBooks_bookKey(bookKey: String) {
        fetchValueStore().deleteObject(byId: bookKey, fromTable: bookTableName())
    }
    private func allBooksCount_bookKey(bookKey: String) -> Int {
        let dicBooks: Array<[String: String]> = getAlldicBooks_bookKey(bookKey: bookKey)
        return dicBooks.count
    }


    ///#pragma mark -  - 存储书单
    ///存储一个书单
    func saveHomeBookInfoModel(infoModel: BookModel) {
        saveBookInfoModel(infoModel: infoModel, bookKey: bookKey())
    }
    ///取出一个书单
    func getHomeBook(book_id: String) -> BookModel {
        return getBook(book_id: book_id, bookKey: bookKey())
    }
    ///取出所有书单
    func getAllHomeBooks() -> Array<BookModel> {
        return getAllBooks_bookKey(bookKey: bookKey())
    }
    ///删除一个书单
    func deleteHomeBook(book_id: String) {
        deleteBook(book_id: book_id, bookKey: bookKey())
    }
    ///删除所有书单
    func deleteAllHomeBooks() {
        deleteAllBooks_bookKey(bookKey: bookKey())
    }
    ///取出书单数量
    func allHomeBooksCount() -> Int {
        return allBooksCount_bookKey(bookKey: bookKey())
    }

    ///#pragma mark - 添加书单
    ///添加一个书单到添加列表
    func saveAddBookInfoModel(infoModel: BookModel) {
        saveBookInfoModel(infoModel: infoModel, bookKey: bookAddKey())
    }
    ///从添加列表取出一个书单
    func getAddBook(book_id: String) -> BookModel {
        return getBook(book_id: book_id, bookKey: bookAddKey())
    }
    ///从添加列表取出所有书单
    func getAllAddBooks() -> Array<BookModel> {
        return getAllBooks_bookKey(bookKey: bookAddKey())
    }
    ///从添加列表删除一个书单
    func deleteAddBook(book_id: String) {
        deleteBook(book_id: book_id, bookKey: bookAddKey())
    }
    ///从添加列表删除所有书单
    func deleteAllAddBooks() {
        deleteAllBooks_bookKey(bookKey: bookAddKey())
    }
    ///从添加列表查询书单数量
    func allAddBooksCount() -> Int {
        return allBooksCount_bookKey(bookKey: bookAddKey())
    }


    ///#pragma mark - 完成书单
    ///添加一个书单到完成列表
    func saveFinishBookInfoModel(infoModel: BookModel) {
        saveBookInfoModel(infoModel: infoModel, bookKey: bookFinishKey())
    }
    ///从完成列表取出一个书单
    func getFinishBook(book_id: String) -> BookModel {
        return getBook(book_id: book_id, bookKey: bookFinishKey())
    }
    ///从完成列表取出所有书单
    func getAllFinishBooks() -> Array<BookModel> {
        return getAllBooks_bookKey(bookKey: bookFinishKey())
    }
    ///从完成列表删除一个书单
    func deleteFinishBook(book_id: String) {
        deleteBook(book_id: book_id, bookKey: bookFinishKey())
    }
    ///从完成列表删除所有书单
    func deleteFinishAddBooks() {
        deleteAllBooks_bookKey(bookKey: bookFinishKey())
    }
    ///从完成列表查询书单数量
    func allFinishBooksCount() -> Int {
        return allBooksCount_bookKey(bookKey: bookFinishKey())
    }

    ///#pragma mark -
    ///保存每日提醒时间
    func saveDailyReminder(timeStr: String) {
        fetchValueStore(table: dailyReminderTableName()).put(timeStr, withId: dailyReminderKey(), intoTable: dailyReminderTableName())
    }
    ///得到每日提醒时间
    func getDailyReminder() -> String {
        
        guard fetchValueStore(table: dailyReminderTableName()).getYTKKeyValueItem(byId: dailyReminderKey(), fromTable: dailyReminderTableName()) != nil else {
            return ""
        }
        guard let string = fetchValueStore(table: dailyReminderTableName()).getStringById(dailyReminderKey(), fromTable: dailyReminderTableName()) else {
            return ""
        }
        return string
    }
    ///删除每日提醒时间
    func deleteDailyReminder() {
        
        fetchValueStore(table: dailyReminderTableName()).deleteObject(byId: dailyReminderKey(), fromTable: dailyReminderTableName())
    }

    ///#pragma mark -
    public func saveFirstData() {
        let dicBooks: Array<[String: String]> = getAlldicBooks_bookKey(bookKey: bookKey())
        if (dicBooks.count == 0) {
            let modelTitles = ["添加书单", "西诀", "东霓", "南音"]
            let modelauthors = ["", "笛安", "笛安", "笛安"]
            let modelImageStrs = ["picture_add", "xijue", "dongni", "nanyin"]
            let book_shiyan1 = "家是什么？对于西决来说，家是女朋友陈嫣以及肚子里的孩子，他们正在迈向建立家的路上；对于姐姐东霓来说，家意味着逃离，离开争吵的家庭远赴异国建立自己的属地；对于妹妹南音来说，家暂时不那么重要，她眼中只有她的男孩苏远智；对于小叔郑鸿来说，家早已在十年前那场轰动全校的师生恋中破碎。故事的起点是这座北方城市——龙城郑家，是年，我们见证这个家庭的聚合离散，苦辣欢悲……"
            var i = 0
            for title in modelTitles {
                let model = BookModel.init()
                model.book_id = String(i)
                model.book_title = title
                model.book_author = modelauthors[i]
                model.imageStr = modelImageStrs[i]
                if i == 0 {
                    model.imageType = "-1"
                } else {
                    model.imageType = "0"
                }
                saveHomeBookInfoModel(infoModel: model) 
                
                if i == 1 {
                    model.book_shiyan = book_shiyan1
                    model.addTime = Date().timeStamp
                    model.status = "1"
                    model.progress = "0.11"
                    saveAddBookInfoModel(infoModel: model)
                }
                
                i += 1
            }
        }
    }
    

}

